'''
Created on 2020年5月9日

@author: Kitch
'''

import json
import logging

from fastapi import APIRouter, Header


try:
    from ..libs import example, tools
    from ..registry import *
    from ..models.schema import *
    from ..models import session
except:
    from libs import example, tools
    from registry import *
    from models.schema import *
    from models import session

log = logging.getLogger("example")
router = APIRouter()


@router.get("/example/get", tags=["example"])
async def get_example(id: int = None, timestamp: str = Header(None), sign: str = Header(None)):
    """ return the object if the id exist
        or return the object list
    """
    try:
        log.info(f"get_example, id: {id}")
        await tools.check_sign(id, timestamp=timestamp, sign=sign)
        r = await example.get(id)
        if type(r) is list:
            return [tools.obj2dict(itm) for itm in r]
        else:
            return tools.obj2dict(r)
    except:
        log.exception("get_example: ")
    finally:
        session.rollback()


@router.post("/example/add", tags=["example"])
async def example_add(es: ExampleSchema, 
                      timestamp: str = Header(None), sign: str = Header(None)):
    """ add
    """
    result = {"status": 0}
    try:
        log.info(f"example_add: {es}")
        await tools.check_sign(es.id, es.name, es.notes, timestamp=timestamp, sign=sign)
        try:
            await example.add_edit(es.id, es.name, es.notes)
            session.commit()
        except:
            log.exception("example_add: db")
            session.rollback()
        result["status"] = 1
    except:
        log.exception("example_add: ")
    finally:
        session.rollback()
    log.info(f"example_add: {es.id}, {result['status']}")
    return result


@router.post("/example/edit", tags=["example"])
async def example_edit(es: ExampleSchema, 
                       timestamp: str = Header(None), sign: str = Header(None)):
    """ edit
    """
    result = {"status": 0}
    try:
        log.info(f"example_edit: {es}")
        await tools.check_sign(es.id, es.name, es.notes, timestamp=timestamp, sign=sign)
        try:
            e = await example.get(es.id)
            if e:
                await example.add_edit(es.id, es.name, es.notes)
                session.commit()
            else:
                result["status"] = 2
        except:
            log.exception("example_edit: db")
            session.rollback()
        result["status"] = 1
    except:
        log.exception("example_edit: ")
    finally:
        session.rollback()
    log.info(f"example_edit: {es.id}, {result['status']}")
    return result


@router.post("/example/delete", tags=["example"])
async def example_delete(es: ExampleSchema, 
                         timestamp: str = Header(None), sign: str = Header(None)):
    """ delete
    """
    result = {"status": 0}
    try:
        log.info(f"example_delete: {es}")
        await tools.check_sign(es.id, timestamp=timestamp, sign=sign)
        try:
            await example.delete(es.id)
            session.commit()
        except:
            log.exception("example_delete: db")
            session.rollback()
        result["status"] = 1
    except:
        log.exception("example_delete: ")
    finally:
        session.rollback()
    log.info(f"example_delete: {es.id}, {result['status']}")
    return result
